package pzl.mn.practice.live_data;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import androidx.lifecycle.LiveData;

import java.lang.ref.WeakReference;

import static android.content.Context.WIFI_SERVICE;

/**
 * wifi数据持有类，观察者生命周期
 */
public class WifiData extends LiveData<String> {
    private static WifiData data;
    private WeakReference<Context> mContextWeakReference;

    private WifiData(Context context) {
        mContextWeakReference = new WeakReference<>(context);
    }

    public static WifiData getInstance(Context context) {
        if (data == null) {
            data = new WifiData(context);
        }
        return data;
    }


    @Override
    protected void onActive() {
        super.onActive();
        registerReceiver();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        unregisterReceiver();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        mContextWeakReference.get().registerReceiver(mReceiver, intentFilter);
    }

    private void unregisterReceiver() {
        mContextWeakReference.get().unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
                WifiInfo info = wifiManager.getConnectionInfo();
                if (info.getBSSID() != null) {
                    // 链接信号强度，100为获取的信号强度值在100以内
                    int strength = WifiManager.calculateSignalLevel(info.getRssi(), 100);
                    // 链接速度
                    int speed = info.getLinkSpeed();
                    // 链接速度单位
                    String units = WifiInfo.LINK_SPEED_UNITS;
                    String text = "WIFI\n " + "强度：" + strength + "\n速度： " + speed + " " + units;
                    data.setValue(text);
                }

            }
        }
    };

}
